﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace commonlib
{
    [Serializable]
    public class DataStore
    {
        public DataStore(DataServer node)
        {
            this.storage = new Dictionary<string, SortedList<long,string>>();
            this.node = node;
        }

        public DataServer node
        {
            get;
            set;
        }

        Dictionary<String, SortedList<long, string>> storage
        {
            get;
            set;
        }

        public void put(String key, String value, long txId)
        {
            if (!storage.ContainsKey(key))
            {
                SortedList<long, string> versions = new SortedList<long, string>();
                versions.Add(txId,value);
                this.storage.Add(key, versions);
            }
            else
            {
                SortedList<long, string> versions = (SortedList<long, string>)this.storage[key];
                versions.Add(txId,value);
                this.storage[key] = versions;
            }
        }

        public Tuple get(String key, long txId)
        {
            Tuple pair=null;

            if (storage.ContainsKey(key))
            {
                SortedList<long, string> versions = (SortedList<long, string>)this.storage[key];
                KeyValuePair<long,string> item= versions.ElementAt(versions.Count-1);
                pair= new Tuple(key,this.node,item.Value,item.Key,0);
            }

            return pair;
        }

        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();

            foreach (KeyValuePair<string, SortedList<long, string>> pair in this.storage)
            {
                builder.Append("Element{ Key: "+pair.Key+" -> {");
                foreach (KeyValuePair<long, string> versions in (SortedList<long, string>)pair.Value)
                {
                    builder.Append("(Value: " + versions.Value + " ; Timestamp:" + versions.Key + "),");
                }

                builder.Remove(builder.Length - 1, 1);// remove a ultima virgula
                builder.Append("}");
            }

            builder.Append("}");
            
            return builder.ToString();
        }

    }
}
